package com.mibao.activity;

import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.mibao.db.DBAdapter;
import com.mipai.R;

/**
 * @author xieyinchao
 * @todo 设置密码
 */
public class GuideActivity extends Activity {
	private Button sureButton = null;
	private TextView newpwd = null;
	private TextView renewpwd = null;
	private TextView guide_sure_tip = null;

	private SharedPreferences preferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		preferences = getSharedPreferences("first_pref", MODE_PRIVATE);
		setContentView(R.layout.guide);		
		newpwd = (TextView) findViewById(R.id.surepwd);
		renewpwd = (TextView) findViewById(R.id.resurepwd);
		guide_sure_tip = (TextView) findViewById(R.id.guid_pwd_tip);
		// 绑定确认按钮
		sureButton = (Button) findViewById(R.id.guid_sure);
		sureButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				String newPwdStr = newpwd.getText().toString();
				String reNewPwdStr = renewpwd.getText().toString();
				if (!newPwdStr.equals("") && !reNewPwdStr.equals("")) {
					if (newPwdStr.equals(reNewPwdStr)) {
						boolean isNum1 = this.isNumeric(newPwdStr);
						boolean isNum2 = this.isNumeric(reNewPwdStr);
						if (isNum1 && isNum2) {
							DBAdapter dao = new DBAdapter(GuideActivity.this).open();
							boolean flag = dao.insertPwd(reNewPwdStr);
							if (flag) {
								guide_sure_tip.setText("设置密码成功！");
								// ///////保存设置的密码///////////
								String pwd = newpwd.getText().toString();
								Editor editor = preferences.edit();
								editor.putString("password", pwd);
								// /////////////////
								editor.putBoolean("isFirstIn", false);
								editor.commit();
								// 跳转Activity
								Intent intent = new Intent(GuideActivity.this, SetEmailActivity.class);
								System.out.println(intent);
								startActivity(intent);
								finish();
							} else {
								guide_sure_tip.setText("设置密码失败！");
							}
							dao.close();
						} else {
							guide_sure_tip.setText("请输入数字！");
						}
					} else {
						guide_sure_tip.setText("重复密码错误，请重新输入密码！");
					}
				} else {
					guide_sure_tip.setText("密码不能为空！");
				}
			}
			private boolean isNumeric(String str) {
				Pattern pattern = Pattern.compile("[0-9]*");
				return pattern.matcher(str).matches();
			}
		});
	}
}
